package com.sxhnpg.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;



/**
 * <p>Description:
 *		登录过滤身份检测，检查是否非匿名用户访问安全资源
 * </p>
 * @exist_problem
 * @amendment_history
 */
public class LoginFilter implements Filter {
	
	private Log log = LogFactory.getLog(LoginFilter.class);
	// 允许匿名访问的路径列表
	private List<String> unRedirectList = new ArrayList<String>();;
	
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		if ( !(request instanceof HttpServletRequest)
				|| !(response instanceof HttpServletResponse) )
			throw new ServletException("LoginFilter just supports HTTP requests");
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		String contextPath = httpRequest.getContextPath();
		String requestURI = httpRequest.getRequestURI();
		requestURI = requestURI.substring(requestURI.indexOf(contextPath) + contextPath.length());
		
		HttpSession session = httpRequest.getSession(false);
		// 为了防止用户登录后再次重登陆，所以访问登录页面时直接让用户访问登录后首页(只针对用户)
		if( requestURI.equals("/index.jsp") || requestURI.equals("/")){
			if ( session != null && session.getAttribute("login_user") != null ) {
				httpResponse.sendRedirect(contextPath + "/pages/travelAgencyInfo/travelOpt!travelList.do");
				return;
			}
		}
		
		// 检查 所请求的路径是否允许匿名访问
		for ( int i = 0; i < unRedirectList.size(); i++ )
			if ( requestURI.equals((String)unRedirectList.get(i)) ) {
				chain.doFilter(request, response);
				return;
			}
		
		
		// 检查session用户登录信息是否有效
		if (requestURI.startsWith("/pages/") || requestURI.startsWith("/commons/")) {
			if (session != null && session.getAttribute("login_user") != null) {
				chain.doFilter(request, response);
				return;
			}
		} else {
			chain.doFilter(request, response);
			return;
		}
			
		
		// 强制返回系统首页
		httpResponse.sendRedirect(contextPath);
		
	}
	
	
	public void init(FilterConfig filterConfig) throws ServletException {
		// 允许匿名访问的路径列表 （在此初始化）
		unRedirectList.add("/");
		unRedirectList.add("/index.jsp");
		unRedirectList.add("/commons/footer.jsp");
		unRedirectList.add("/commons/loginHeader.jsp");
		unRedirectList.add("/commons/meta.jsp");
		unRedirectList.add("/commons/taglibs.jsp");
		
	}
	
	public void destroy() {
	}

}